# -*- coding: utf-8 -*-
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from emof import core as EMOF
from emof import dumper
from emof import loader

from model import Model

class LoadCommentData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        c_id = self.request.get("id")
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        self.response.headers['Content-Type'] = 'application/xml'
        xml = "<r></r>"
        
        cmm = rep.findComment(c_id)
        
        template_values = {'id': c_id,
                           'cmm': cmm}
        
        path = os.path.join(os.getcwd(), 'xml/Comment.xml')
        xml = template.render(path, template_values)

        self.response.out.write(xml)
                
class SaveCommentData(webapp.RequestHandler):
    def post(self):
        m_id = self.request.get("m_id")
        c_id = self.request.get("id")
        body = self.request.get("body")
        annotatedElements = self.request.get_all("annotatedElement")
        
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)

        cmm = rep.findComment(c_id)
        cmm.body = body
        
        annotatedElement = list()
        
        for aex in cmm.annotatedElement:
            aex.ownedComment.remove(cmm)
        
        if annotatedElements:
            for ae in annotatedElements:
                el = rep.findElement(ae)
                if el:
                    annotatedElement.append(el)
                    el.ownedComment.append(cmm)
        
        cmm.annotatedElement = annotatedElement
        
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
                
        self.response.out.write("OK")
        
class CreateCommentData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        
        if self.request.get("p_id") != "":
            p_id = self.request.get("p_id")
        else:
            p_id = '-1'
            
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        fact = EMOF.Factory(rep)
        cm = fact.create_Comment()
        
        el = rep.findElement(p_id)
        
        if el:
            cm.annotatedElement.append(el)
            el.ownedComment.append(cm)
        
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
                
        self.response.out.write(cm.id + '$$$$' + cm._xmi_id)